﻿
using ZX.Common;
using ZX.DBModule;
using ZX.BLL.Extend;
using ZX.SYS.Library;
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using ZX.BPM.Library;


namespace ZX.Web.UI.Controls
{
    public partial class AutoLoadForm : EditUIPage
    {
        /// <summary>
        /// 流程状态
        /// </summary>
        public string Status
        {
            get;
            set;
        }




        public string FlowCaption
        {
            get;
            set;
        }
        /// <summary>
        /// 弹出列表客户经理ID
        /// </summary>
        public string addUser { get { return this.UserId.ToString(); } }

        protected void Page_Load(object sender, EventArgs e)
        {
            CreateUI();
        }


        BaseEntity MasterEntity = null; 
        private void CreateUI()
        {
            string strEntity = this.GetStringFromQueryString("entity", "E_Menu");
            string action = this.GetStringFromQueryString("action", "");
            string strFormID = this.GetStringFromQueryString("formid", Guid.Empty.ToString());
            string strWorkFlowId=this.GetStringFromQueryString("workflowid", "");
            string strWorkTaskId=this.GetStringFromQueryString("worktaskid", "");
            FlowCaption =Server.UrlDecode(this.GetStringFromQueryString("FlowCaption",""));
            Status = this.GetStringFromQueryString("statues", "");
            string id = this.GetStringFromQueryString("id", "");
            BaseEntity instance = ZX.Common.Globals.getEntity(strEntity) as BaseEntity;


            MasterEntity = instance;
            BaseBussnies bInstance = new BLL.Extend.BaseBussnies(instance);
            BaseEntity entity = null;
            string strDefaultPropertyValues = "";
            string WorkTaskFormRoles = "";
            string strWorkTaskTitle = "";
            if (instance == null)
            {
                instance = new DataTableBaseEntity();
                ((DataTableBaseEntity)instance).TableName = strEntity;
                string[] strArrary = ((DataTableBaseEntity)instance).GetKey();
                if (strArrary != null)
                {
                    ((DataTableBaseEntity)instance).TableKey = strArrary[0];
                    ((DataTableBaseEntity)instance).KeyType = strArrary[1];
                }
                ((DataTableBaseEntity)instance).CreateDT();
                //((DataTableBaseEntity)instance).EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)instance).DRow);

                if (id != "") //有ID表示编辑
                {
                    entity = new DataTableBaseEntity(); //bInstance.GetEntityById(id) as BaseEntity;
                    ((DataTableBaseEntity)entity).TableName = strEntity;
                    ((DataTableBaseEntity)entity).TableKey = ((DataTableBaseEntity)instance).TableKey;
                    ((DataTableBaseEntity)entity).KeyType = ((DataTableBaseEntity)instance).KeyType;
                    ((DataTableBaseEntity)entity).CreateDT(id);
                    ((DataTableBaseEntity)entity).EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                    instance = entity;
                }
                else
                {
                    //初始化ID值
                    //KeyValue = instance.GetTableIdValue();
                    if (KeyValue == Guid.Empty.ToString()||String.IsNullOrEmpty(KeyValue) )
                    {
                        ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)instance).TableKey] = Guid.NewGuid();
                    }
                    ((DataTableBaseEntity)instance).EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)instance).DRow);
                    KeyValue = instance.GetTableIdValue(); 
                    strDefaultPropertyValues = CreateDefaultPropertyValues();
                    strWorkTaskTitle=CreateWorkTaskTitle();
                }
               
                if (!string.IsNullOrEmpty(strWorkFlowId) && !string.IsNullOrEmpty(strWorkTaskId))
                {
                    WorkTaskFormRoles = CreateWorkTaskFormRoles(strWorkFlowId, strWorkTaskId, strFormID);
                }
            }
            else
            {
                //初始化ID值
                entity = bInstance.GetEntityById(id) as BaseEntity;
                if (entity != null)
                {
                    instance = entity;
                }
            }
 
            //获取
            if (instance != null)
            {
                object O = instance.GetKeyFieldValue();
                //object O = Globals.GetPropertyValue(instance, instance.GetTableId());
                Guid? _id = ((O) == null) ? null : O as Guid?;
                //初始化ID值
                if (_id == null || _id == Guid.Empty)
                {
                    Globals.SetPropertyValue(instance, instance.GetTableId(), Guid.NewGuid());
                }
            }
            if (!string.IsNullOrEmpty(strWorkFlowId) && !string.IsNullOrEmpty(strWorkTaskId))
            {
                WorkTaskFormRoles = CreateWorkTaskFormRoles(strWorkFlowId, strWorkTaskId, strFormID);
            }

            this.EditTemplate.Text = CreateInstanceJsObject(instance, entity) + strDefaultPropertyValues + WorkTaskFormRoles+strWorkTaskTitle; 
            KeyValue = instance.GetTableIdValue();
            //if (KeyValue == Guid.Empty.ToString())
            //{
            //    ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)instance).TableKey] = Guid.NewGuid();
            //}
            //KeyValue =instance["ID"]; //instance.GetTableId();
            //用于定义相关数据绑定信息
            //用于定义相关数据绑定信息
            /////2012.5.8 汪定新修改------------------------------------------------
            //string tempCondition = strFormID.Trim() == string.Empty || strFormID.Trim() == Guid.Empty.ToString() ? "FormID='" + strFormID + "' or MasterTableName='" + strEntity + "'" : "FormID='" + strFormID + "'";
            //ZX.SYS.Library.SysCustomDefineForm FormEntity = bInstance.GetEntityByCondition<SysCustomDefineForm>(tempCondition);
            //if (FormEntity.MasterTableName != strEntity)
            //{
            //    FormEntity = bInstance.GetEntityByCondition<SysCustomDefineForm>("MasterTableName='" + strEntity + "'");
            //}
            
            //string tempCondition2 = strFormID.Trim() == string.Empty || strFormID.Trim() == Guid.Empty.ToString() ? "FormID='" + strFormID + "' or TableName='" + strEntity + "'" : "FormID='" + strFormID + "'";
            //IList<ZX.SYS.Library.SysFieldItem> dsList = bInstance.GetEntitys<SysFieldItem>(tempCondition2);
            string tempCondition = strFormID.Trim() == string.Empty || strFormID.Trim() == Guid.Empty.ToString() ? "FormID='" + strFormID + "' or MasterTableName='" + strEntity + "'" : "FormID='" + strFormID + "'";
            ZX.SYS.Library.SysCustomDefineForm FormEntity = bInstance.GetEntityByCondition<SysCustomDefineForm>(tempCondition);

            if (FormEntity != null && FormEntity.MasterTableName != strEntity)
            {
                FormEntity = bInstance.GetEntityByCondition<SysCustomDefineForm>("MasterTableName='" + strEntity + "'");
            }

            string tempCondition2 = strFormID.Trim() == string.Empty || strFormID.Trim() == Guid.Empty.ToString() ? "FormID='" + strFormID + "' or TableName='" + strEntity + "'" : "FormID='" + strFormID + "'";
            IList<ZX.SYS.Library.SysFieldItem> dsList = bInstance.GetEntitys<SysFieldItem>(tempCondition2);
            
            
            ///原来的
            //ZX.SYS.Library.SysCustomDefineForm FormEntity = bInstance.GetEntityByCondition<SysCustomDefineForm>("FormID='" + strFormID + "' or MasterTableName='" + strEntity + "'");
            //IList<ZX.SYS.Library.SysFieldItem> dsList = bInstance.GetEntitys<SysFieldItem>("FormID='" + strFormID + "' or TableName='" + strEntity + "'");
            ///------------------------------------------------------------------------------------
            //用于处理

            CreateUIData(dsList);
            if (FormEntity != null) {
                DetailsJson = FormEntity.DetailsJson;
                //Dictionary<string, string> _detail = ZX.Common.Globals.JSonToObject<Dictionary<string, string>>(DetailsJson);
                MasterEntity = instance;
                CreateDetailInstance(DetailsJson);
                FormTemplate.Text = IsMobile ? ChangFormToMobi(FormEntity.HtmlString) : FormEntity.HtmlString;
                this.jSave.Text = ""; //CreateScript(list);
            }
            //this.jInitControl.Text = "";// InitControl(list);
            this.MasterID.Text = SetMasterID();
        }

        public bool IsMobile
        {
            get
            {
                return GetStringFromQueryString("isMobile", "") == "Y";
            }
        }
        /// <summary>
        /// 明细相关数据
        /// </summary>
        public string DetailData
        {
            get;
            set;
        }

        /// <summary>
        /// 不通过Ajax，直接生成明细数据，并返回
        /// </summary>
        public string DetailsListData
        {
            get;
            set;
        }


        private void CreateDetailInstance(string DetailsJson)
        {
            //DetailsJson = FormEntity.DetailsJson;
            if (!string.IsNullOrEmpty(DetailsJson))
            {
                IList<SysDetailsItem> list = ZX.Common.Globals.JSonToObject<IList<SysDetailsItem>>(DetailsJson);
                StringBuilder _details = new StringBuilder("");
                StringBuilder _detailsList = new StringBuilder("");
                foreach (var _detail in list)
                {
                    string table = _detail.DetailsTableName;
                    IList<ZX.SYS.Library.SysFieldItem> dsList = this._bll.GetEntitys<SysFieldItem>("TableName='"+table+"'");
                    DetailData = CreateUIData(dsList, false);
                    DataTableBaseEntity entity = new DataTableBaseEntity(); //bInstance.GetEntityById(id) as BaseEntity;
                    ((DataTableBaseEntity)entity).TableName = table;
                    string[] strArrary = ((DataTableBaseEntity)entity).GetKey();
                    if (strArrary != null)
                    {
                        ((DataTableBaseEntity)entity).TableKey = strArrary[0];
                        ((DataTableBaseEntity)entity).KeyType = strArrary[1];
                    }
                    entity.CreateDT();
                    IList<SysTableFKey> fkList = entity.GetFKey();
                    string _condtion = string.Empty;
                    if (fkList != null)
                    {
                        foreach (var e in fkList)
                        {
                            if (e.FKTableName == MasterEntity.GetTableName())
                            {
                                _condtion = _condtion == string.Empty ? e.FieldName + "='" + KeyValue + "'" : " and " + e.FieldName + "='" + KeyValue + "'";
                                FKExpression = FKExpression + e.FieldName + "='" + KeyValue + "'";
                                entity.SetFieldValue(entity, e.FieldName, KeyValue);
                            }
                        }
                    }
                    else
                    {
                        FKExpression = "1=0";
                    }

                    this._bll.entity = entity;
                    System.Data.DataTable dt = this._bll.GetDataBySqlComm(string.Format("select * from {0} where {1}", table, _condtion));
                    if (dt == null)
                    {
                        _detailsList.Append("var _" + table + "List=[];").AppendLine();
                    }
                    else
                    {
                        _detailsList.Append("var _" + table + "List="+ZX.Common.Globals.Dtb2Json(dt)+";").AppendLine();
                    }
                    ((DataTableBaseEntity)entity).EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                    _details .Append("var " + table + "=" + ((DataTableBaseEntity)entity).EntityJson + ";").AppendLine();
                    //_detailsList.Append("");

                }
                DetailsInstance = _details.ToString() ;
                DetailsListData = _detailsList.ToString();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public string DetailsJson
        {
            get;
            set;
        }
        /// <summary>
        /// 明细表的实体
        /// </summary>
        public string DetailsInstance
        {
            get;
            set;
        }

        /// <summary>
        /// 外键表达式
        /// </summary>
        public string FKExpression
        { 
            get; 
            set; 
        }

        /// <summary>
        /// 主键ID值
        /// </summary>
        public object MasterIDValue
        {
            get;
            set;
        }
        /// <summary>
        /// 行为参数
        /// </summary>
        public String Action
        {
            get
            {
                return this.GetStringFromQueryString("action", "");
            }

        }

        public String KeyValue
        {
            set;
            get;
        }
        /// <summary>
        /// 生成对应的下拉数据
        /// </summary>
        /// <param name="fieldList"></param>
        private void CreateUIData(IList<ZX.SYS.Library.SysFieldItem> fieldList)
        {
            this.jInitControl.Text = "";
            this.jInitControl.Text = CreateUIData(fieldList,true);
        }
        private string CrateUIData(IList<ZX.SYS.Library.SysFieldItem> fieldList,string TableName, bool IsMasterData)
        {
            return "";
        }


        /// <summary>
        /// 生成页面所需的常用数据，例如：下拉框所需的数据
        /// </summary>
        /// <param name="fieldList"></param>
        /// <param name="IsMasterData"></param>
        /// <returns></returns>
        private string CreateUIData(IList<ZX.SYS.Library.SysFieldItem> fieldList,bool IsMasterData)
        {
            if (fieldList == null)
            {
                return "";
            }
            StringBuilder strHtml = new StringBuilder("");
            foreach (var e in fieldList)
            {
                string _cFieldName = IsMasterData ? e.FieldName : "Detail_" + e.FieldName;
                IList<Dictionary> list = null;
                if (e.DataSourceType.ToLower() == "json")
                {
                    strHtml.Append("var ds_" + _cFieldName + "=" + e.DataSource + ";\r\n");
                    list = Globals.JSonToObject<IList<Dictionary>>(e.DataSource);
                    if (IsMasterData)
                    {
                        string str = "";
                        if (e.ControlsType == "select")
                        {
                            str = "$('#" + _cFieldName + "').comBind(ds_" + _cFieldName + ",\"ValueMember\",\"DisplayMember\");\r\n";
                        }
                        else
                        {
                            str = "createComboBox('" + _cFieldName + "', { itemSource: ds_" + _cFieldName + ", style: 'dropdown', autoComplete: 'local' });\r\n";
                        }
                        //string str= "$('#"+ e.FieldName+"').comBind(ds_"+e.FieldName+",\"ValueMember\",\"DisplayMember\");";
                        strHtml.Append(str);
                    }
                }
                if (e.DataSourceType.ToLower() == "sql")
                {
                    strHtml.Append("var ds_" + _cFieldName + "=");
                    BaseBussnies instance = new BaseBussnies();
                    list = instance.GetEntitysBySqlComm<Dictionary>(e.DataSource.Replace("[B]", "'"));
                    if (list != null)
                    {
                        strHtml.Append(Globals.ObjectToJSON(list) + ";");
                        if (IsMasterData)
                        {
                            string str = "";
                            if (e.ControlsType == "select")
                            {
                                str = "$('#" + _cFieldName + "').comBind(ds_" + _cFieldName + ",\"ValueMember\",\"DisplayMember\");\r\n";
                            }
                            else
                            {
                                str = "createComboBox('" + _cFieldName + "', { itemSource: ds_" + _cFieldName + ", style: 'dropdown', autoComplete: 'local' });\r\n";
                            }
                            //string str = "$('#" + e.FieldName + "').comBind(ds_" + e.FieldName + ",\"ValueMember\",\"DisplayMember\");\r\n";
                            strHtml.Append(str);
                        }
                    }
                    else
                    {
                        strHtml.Append("[];\r\n");
                    }

                }
                if (e.DataSourceType.ToLower() == "dic")
                {
                    strHtml.Append("var ds_" + _cFieldName + "=");
                    BaseBussnies instance = new BaseBussnies();
                    list = instance.GetEntitysBySqlComm<Dictionary>(string.Format("Exec [dbo].[sp_GetDicList] '{0}'", e.DataSource));
                    if (list != null)
                    {
                        strHtml.Append(Globals.ObjectToJSON(list) + ";\r\n");
                        if (IsMasterData)
                        {
                            string str = "";
                            if (e.ControlsType == "select")
                            {
                                str = "$('#" + _cFieldName + "').comBind(ds_" + _cFieldName + ",\"ValueMember\",\"DisplayMember\");\r\n";
                            }
                            else
                            {
                                str = "createComboBox('" + _cFieldName + "', { itemSource: ds_" + _cFieldName + ", style: 'dropdown', autoComplete: 'local' });\r\n";
                            }
                            strHtml.Append(str);
                        }
                        
                    }
                    else
                    {
                        strHtml.Append("[];\r\n");
                    }
                }
               
                //return string.Format(strSControl, e.FieldName, strHtml.ToString(), width);
            }
            return strHtml.ToString();
        }
        private string CreateWorkTaskFormRoles(string xWorkFlowId, string xWorkTaskId, string xFormID)
        {
            string _formRoles = "";
            string _DetailsFormRoles ="";
            WorkTaskFormRoles fr = new WorkTaskFormRoles(xWorkFlowId, xWorkTaskId, xFormID);
            Hashtable ht=fr.DetailsPropertyValue;
            foreach (DictionaryEntry de in ht)  
            {  
               _DetailsFormRoles ="  var DetailsFormRoles=" + de.Value.ToString();  
            } 

            string _MasterFormRoles = " var MasterFormRoles=" + ZX.Common.Globals.ObjectToJSON(fr.MasterPropertyValue) +";";
           // string _DetailsFormRoles = "  var DetailsFormRoles=" + 
            return _formRoles = _MasterFormRoles + _DetailsFormRoles;
        }


        private string CreateWorkTaskTitle() 
        {
            string workTaskTitle = "";
            string _title = FlowCaption + "-" + this.EmpPropertyValues.Proposer + "-" + "["+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+"]";
            workTaskTitle = "; var TaskTitle=\"" + _title + "\"";
            return workTaskTitle;
        }

        public string strWorkFlowId
        {
            get
            {
                string wtid = this.GetStringFromQueryString("WorkflowId", "");
                if (wtid == "")
                {
                    wtid = this.GetStringFromQueryString("wfid", "");
                }
                return wtid;
            }
        }
        public string strWorkTaskId
        {
            get
            {
                string wfid = this.GetStringFromQueryString("WorktaskId", "");
                if (wfid == "")
                {
                    wfid = this.GetStringFromQueryString("wtid", "");
                }
                return wfid;
            }
        }
        public string strOperatorInstanceId
        {
            get
            {
                string oid = this.GetStringFromQueryString("OperatorInstanceId", "");
                if (oid == "")
                {
                    oid = Guid.NewGuid().ToString();
                }
                return oid;
            }
        }
        public string strWorkflowInsId
        {
            get
            {
                string wfisd = this.GetStringFromQueryString("WorkflowInsId", "");
                if (wfisd == "")
                {
                    wfisd = Guid.NewGuid().ToString();
                    System.Web.HttpContext.Current.Session["workinsid"]=wfisd;
                   
                }
                return wfisd;
            }
        }
        public string strWorkTaskInsId
        {
            get
            {
                string wtisd = this.GetStringFromQueryString("WorktaskInsId", "");
                if (wtisd == "")
                {
                    wtisd = Guid.NewGuid().ToString();
                    System.Web.HttpContext.Current.Session["worktasid"]=wtisd;
                }
                return wtisd;
            }
        }
    }
}
